﻿// Modules/ModuleName/ViewModels/ExistingPageViewModel.cs
using Prism.Commands;
using Prism.Mvvm;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Data;
using Microsoft.Win32;
using System.ComponentModel;
using System.Threading.Tasks;
using System;
using Prism.Regions;
using System.Diagnostics;
using System.Windows.Input;
using FullApp1.Services;
using FullApp1.Modules.ModuleName.Models;

namespace FullApp1.Modules.ModuleName.ViewModels
{
    public class ExistingPageViewModel : BindableBase, INavigationAware
    {
        // 依赖注入字段
        private readonly IExportService _exportService;
        private readonly IRegionManager _regionManager;

        

        // 构造函数
        public ExistingPageViewModel(IExportService exportService, IRegionManager regionManager)
        {
            _exportService = exportService;
            _regionManager = regionManager ?? throw new ArgumentNullException(nameof(regionManager));

            // 初始化集合
            Licenses = new ObservableCollection<LicenseInfo>();
            FilteredLicenses = CollectionViewSource.GetDefaultView(Licenses);
            FilteredLicenses.Filter = FilterLicenses;

            SelectLicenseCommand = new DelegateCommand<LicenseInfo>(licenseInfo =>
               SelectedLicense = licenseInfo);

            EditCommand = new DelegateCommand(() => IsEditing = true);
            CancelCommand = new DelegateCommand(() =>
            {
                IsEditing = false;
            });
            SaveCommand = new DelegateCommand(() =>
            {
                // 保存逻辑
                IsEditing = false;
            });

            // 初始化其他命令（如分页按钮）
            InitializeCommands();

            // 加载数据
            LoadSampleData();
        }
        
        // 其他属性和字段...
        private LicenseInfo _selectedLicense;
        public LicenseInfo SelectedLicense
        {
            get => _selectedLicense;
            set => SetProperty(ref _selectedLicense, value);
        }

        // 编辑状态
        private bool _isEditing;
        public bool IsEditing
        {
            get => _isEditing;
            set => SetProperty(ref _isEditing, value);
        }

        private string _searchText;
        public string SearchText
        {
            get => _searchText;
            set => SetProperty(ref _searchText, value);
        }

        private bool _isLoading;
        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        private int _currentPage = 1;
        public int CurrentPage
        {
            get => _currentPage;
            set => SetProperty(ref _currentPage, value);
        }
        private bool _isScrolling;
        public bool IsScrolling
        {
            get => _isScrolling;
            set => SetProperty(ref _isScrolling, value);
        }

        private double _verticalOffset;
        public double VerticalOffset
        {
            get => _verticalOffset;
            set => SetProperty(ref _verticalOffset, value);
        }

        private int _totalPages = 10;
        public int TotalPages
        {
            get => _totalPages;
            set => SetProperty(ref _totalPages, value);
        }


        public ICommand SingleClickCommand { get; }
        // 命令定义
        public DelegateCommand<LicenseInfo> SelectLicenseCommand { get; }
        public DelegateCommand EditCommand { get; }
        public DelegateCommand SaveCommand { get; }
        public DelegateCommand ApplyCommand { get; set; }
        public DelegateCommand ModifyCommand { get; set; }
        public DelegateCommand CancelCommand { get; set; }
        public DelegateCommand AnnualCheckCommand { get; set; }
        public DelegateCommand ExportCommand { get; set; }
        public DelegateCommand SearchCommand { get; set; }
        public DelegateCommand FirstPageCommand { get; set; }
        public DelegateCommand PreviousPageCommand { get; set; }
        public DelegateCommand NextPageCommand { get; set; }
        public DelegateCommand LastPageCommand { get; set; }

        private void InitializeCommands()
        {
            // 分页命令
            FirstPageCommand = new DelegateCommand(
                () => CurrentPage = 1,
                () => CurrentPage > 1
            ).ObservesProperty(() => CurrentPage);

            PreviousPageCommand = new DelegateCommand(
                () => CurrentPage--,
                () => CurrentPage > 1
            ).ObservesProperty(() => CurrentPage);

            NextPageCommand = new DelegateCommand(
                () => CurrentPage++,
                () => CurrentPage < TotalPages
            ).ObservesProperty(() => CurrentPage);

            LastPageCommand = new DelegateCommand(
                () => CurrentPage = TotalPages,
                () => CurrentPage < TotalPages
            ).ObservesProperty(() => CurrentPage);

            // 其他核心命令
            SearchCommand = new DelegateCommand(ExecuteSearch);
            ExportCommand = new DelegateCommand(ExecuteExport);
        }
        
        private bool FilterLicenses(object item)
        {
            if (string.IsNullOrWhiteSpace(SearchText)) return true;

            var license = (LicenseInfo)item;
            return license.Name.Contains(SearchText) ||
                   license.UnifiedSocialCode.Contains(SearchText);
        }

        // 修改LoadSampleData方法中的数据生成部分
        private async void LoadSampleData()
        {
            try
            {
                IsLoading = true;
                await Task.Delay(1000); // 模拟服务延迟

                // 安全生成数据
                var newData = Enumerable.Range(1, 50)
                    .Select(i => new LicenseInfo
                    {
                        UnifiedSocialCode = $"CODE{i:000}",
                        Name = $"企业名称{i}",
                        legalPerson = new LegalPerson
                        {
                            Name = $"法人{i}",
                            IDNumber = $"ID{i:000000000000000000}",
                            Phone = $"138-{i:0000}-{i:0000}"
                        }
                    })
                    .ToList();

                Licenses.Clear();
                Licenses.AddRange(newData);

                // 更新分页总数
                TotalPages = 5; // 示例值，应根据实际数据计算
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"数据加载失败: {ex.Message}");
            }
            finally
            {
                IsLoading = false;
                FilteredLicenses.Refresh();
            }
        }

        private void ExecuteSearch() => FilteredLicenses.Refresh();

        /// <summary>
        /// 到出到Excel文件
        /// </summary>
        private void ExecuteExport()
        {
            var saveDialog = new SaveFileDialog
            {
                Filter = "Excel文件|*.xlsx",
                FileName = $"企业数据导出_{DateTime.Now:yyyyMMdd}.xlsx"
            };

            if (saveDialog.ShowDialog() == true)
            {
                _exportService.ExportToExcel(FilteredLicenses.Cast<LicenseInfo>(), saveDialog.FileName);
            }
        }

        public ObservableCollection<LicenseInfo> Licenses { get; }
        public ICollectionView FilteredLicenses { get; }

        


        //NavigateToDetail方法
        private void NavigateToDetail(object parameter)
        {            
            Debug.WriteLine("导航执行");
            // 添加空值检查
            if (parameter == null)
            {
                Debug.WriteLine("导航参数 license 为空");
                return;
            }

            // 使用更安全的参数构造方式
            var navParams = new NavigationParameters
            {
                { "selectedLicense", (LicenseInfo)parameter },
                { "sourceState", new NavigationParameters
                    {
                        { "searchText", SearchText },
                        { "currentPage", CurrentPage.ToString() },
                        { "scrollOffset", VerticalOffset.ToString() }
                    }
                }
            };

            //_regionManager.RequestNavigate("ContentRegion", "LicenseDetail", navParams);

            //添加导航结果检查
            _regionManager.RequestNavigate(
                "ContentRegion",
                new Uri("LicenseDetail", UriKind.Relative), // ✅ Uri 强制包装                
                result => // ✅ 回调函数位于参数3
                {
                    if (result.Error != null)
                        Debug.WriteLine($"导航异常: {result.Error}");
                },
                navParams // ✅ 导航参数位于参数4
            );
        }

        // 修改RestoreState方法
        public void RestoreState(NavigationParameters parameters)
        {
            if (parameters != null)
            {
                // 安全获取参数值
                SearchText = parameters.GetValue<string>("searchText") ?? string.Empty;

                // 转换分页参数
                if (int.TryParse(parameters.GetValue<string>("currentPage"), out int page))
                    CurrentPage = page;

                // 转换滚动位置
                if (double.TryParse(parameters.GetValue<string>("scrollOffset"), out double offset))
                    VerticalOffset = offset;

                // 异步刷新数据
                Task.Run(() => FilteredLicenses.Refresh());
            }
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            // 检查是否有恢复参数
            if (navigationContext.Parameters.TryGetValue("restoreState", out NavigationParameters parameters))
            {
                RestoreState(parameters);
            }
        }

        /// <summary>
        /// 是否重用当前实例
        /// </summary>
        public bool IsNavigationTarget(NavigationContext navigationContext) => true;

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            // 正确做法：创建新参数对象
            var newParams = new NavigationParameters
            {
                { "returnState", new NavigationParameters
                    {
                        { "searchText", SearchText },
                        { "currentPage", CurrentPage.ToString() },
                        { "scrollOffset", VerticalOffset.ToString() }
                    }
                }
            };

            // 合并原始参数（如果需要）
            foreach (var pair in navigationContext.Parameters)
            {
                if (!newParams.ContainsKey(pair.Key))
                {
                    newParams.Add(pair.Key, pair.Value);
                }
            }

            // 重新导航（仅示例，实际应通过导航服务传递）
            //_regionManager.RequestNavigate(
            //    navigationContext.NavigationService.Region.Name,
            //    navigationContext.NavigationService.CurrentUri.ToString(),
            //    newParams
            //);
        }
    }

    
    // 其他命令实现...

}


